<?php
/**
 * Description of CTemplate
 *
 * @author root
 */
namespace TwinPeaks\Core;

abstract class CTemplate
{
	use TAppInjector;

	/**
	 * @var string
	 */
	private $tplFilename;
	
	/**
	 * @var string
	 */
	private $mockDataFilename;
	
	/**
	 * @var
	 */
	private $context;

	/**
	 * @var CFrontController Front controller instance
	 */
	private $fcInstance;
	
	/**
	 * @var CRule Matched rule instance
	 */
	private $ruleInstance;
	
	//
	private $layout;
	
	/**
	 * @return void
	 */
	protected function __construct($tplFilename, $context = null)
	{
		$app = self::getApplication();
		$config = $app->getConfig();

		$this->tplFilename = $app->resolvePath($tplFilename) . '.tpl.php';
		if (!$context)
		{
			$this->context = new CContext($this);
			if (($config->_mock_page_all || $config->_mock_page === $tplFilename) &&
				$config->debugMode && ($mockDataFilename = $this->getMockDataFilename()) != null)
			{
				$mockData = require($app->resolvePath(($mockDataFilename) . '.data.php'));
				$this->context->setData($mockData);
			}
		}
		else
		{			
			$context->setTemplate($this);
			$this->context = $context;
		}
	}
	
	/**
	 * @return null
	 */
	protected function getMockDataFilename()
	{
		return null;
	}
	
	/**
	 * @return CRule
	 */
	final function getCurrentRule()
	{
		return self::getApplication()->getCurrentRule();
	}
	
	/**
	 * @return string
	 */
	function getTplFilename()
	{
		return $this->tplFilename;
	}
	
	function setLayout($layout)
	{
		$this->layout = $layout;
	}
	
	function getLayout()
	{
		return $this->layout;
	}
	
	/**
	 * @final
	 * @return
	 */
	final function getContext()
	{
		return $this->context;
	}
	
	/**
	 * @return void
	 */
	final function render()
	{
		$c = $this->getContext(); // Template context
		$ctx = $this->getContext();
		require $this->tplFilename;
		unset($c);
	}
	
	function __toString()
	{
		ob_start();
		$this->render();
		return ob_get_clean();
	}
}
